package com.hoow.shakoow.utils

import android.annotation.SuppressLint
import com.hoow.shakoow.extend.dateForFormatString
import com.hoow.shakoow.extend.dateFormatString
import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.TimeUnit

object DateUtil {

    /** 获取时间格式化描述 */
    @SuppressLint("SimpleDateFormat")
    fun getTimeAgo(timestampString: String): String {
        if (timestampString.isNotBlank()) {
            try {
                val timestamp = timestampString.toLong()
                val currentTimeMillis = System.currentTimeMillis()
                val diffInMillis = currentTimeMillis - timestamp

                val seconds = TimeUnit.MILLISECONDS.toSeconds(diffInMillis)
                val minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMillis)
                val hours = TimeUnit.MILLISECONDS.toHours(diffInMillis)
                val days = TimeUnit.MILLISECONDS.toDays(diffInMillis)

                return when {
                    seconds < 60 -> "Just now"
                    minutes < 60 -> "$minutes minutes ago"
                    hours < 24 -> "$hours hours ago"
                    days < 7 -> "$days days ago"
                    else -> SimpleDateFormat("yyyy-MM-dd").format(Date(timestamp))
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return ""
    }

    /** 获取时间格式化描述 */
    @SuppressLint("SimpleDateFormat")
    fun getTimeAgoFromDateString(
        dateString: String,
        dateFormat: String = "yyyy-MM-dd hh:mm:ss"
    ): String {

        try {
            if (dateString.isNotBlank()) {
                val gDate = dateString.dateForFormatString(dateFormat)
                gDate?.let { safeDate ->
                    val timestamp = safeDate.time
                    val currentTimeMillis = System.currentTimeMillis()
                    val diffInMillis = currentTimeMillis - timestamp

                    val seconds = TimeUnit.MILLISECONDS.toSeconds(diffInMillis)
                    val minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMillis)
                    val hours = TimeUnit.MILLISECONDS.toHours(diffInMillis)
                    val days = TimeUnit.MILLISECONDS.toDays(diffInMillis)

                    return when {
                        seconds < 60 -> "Just now"
                        minutes < 60 -> "$minutes minutes ago"
                        hours < 24 -> "$hours hours ago"
                        days < 7 -> "$days days ago"
                        else -> SimpleDateFormat("yyyy-MM-dd").format(Date(timestamp))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return dateString
    }
}